<?php
function bs_import_feeds()
{
	global $wpdb;
	
	$options = get_option( 'bs-general-options' );
	$providers_count = isset($options['providers']) ? count($options['providers']) : 0;
	
	for ( $i = 0; $i < $providers_count; $i++ )
	{
		$provider_name = $options['providers'][$i]['name'];
		$provider_source = $options['providers'][$i]['source'];
		
		if ( $provider_source )
		{
			$rss = fetch_feed($provider_source);
			
			if ( ! is_wp_error($rss) )
			{
				$maxitems = $rss->get_item_quantity(5);
				$rss_items = $rss->get_items(0, $maxitems);
				
				foreach( $rss_items as $item )
				{
					$title = esc_html( $item->get_title() );
					
					if ( ! bs_is_duplicate_feed($title, $provider_name) )
					{
						$datetime = $item->get_date('Y-m-d H:i:s'); 
						$excerpt = $item->get_description(true);
						$content = $item->get_content();
						$source = esc_url( $item->get_permalink() );
						
						$featured_image = '';
						$attachments = bs_get_attachments_url_on_content( $content );
						if ( $attachments )
						{
							$featured_image = $attachments[0]['guid'];
						}
						
						$wpdb->insert(
							'bs_custom_feeds',
							array(
								'title' => $title,
								'datetime' => $datetime,
								'excerpt' => $excerpt,
								'featuredimage' => $featured_image,
								'content' => $content,
								'source' => $source,
								'provider' => $provider_name
							),
							array(
								'%s',
								'%s',
								'%s',
								'%s',
								'%s',
								'%s',
								'%s'
							)
						);
					}
				}
			}
		}
	}
}